document.addEventListener('DOMContentLoaded', function() {
    const addUrlBtn = document.getElementById('add-url');
    const urlInput = document.getElementById('url');
    const nameInput = document.getElementById('name');
    const urlList = document.getElementById('url-list');

    // 加载已保存的地址
    loadUrls();

    addUrlBtn.addEventListener('click', function() {
        const url = urlInput.value.trim();
        const name = nameInput.value.trim();

        if (url && name) {
            saveUrl(name, url);
            urlInput.value = '';
            nameInput.value = '';
            loadUrls();
        }
    });

    function saveUrl(name, url) {
        chrome.storage.local.get('requestUrls', function(data) {
            const urls = data.requestUrls || {};
            urls[name] = url;
            chrome.storage.local.set({'requestUrls': urls}, function() {
                console.log('地址已保存:', name, url);
            });
        });
    }

    function loadUrls() {
        chrome.storage.local.get('requestUrls', function(data) {
            const urls = data.requestUrls || {};
            urlList.innerHTML = '';

            for (const name in urls) {
                const url = urls[name];
                const urlItem = document.createElement('div');
                urlItem.className = 'url-item';
                urlItem.innerHTML = `
                    <span>${name}: ${url}</span>
                    <button class="delete-btn" data-name="${name}">删除</button>
                    <button class="activate-btn" data-url="${url}">激活</button>
                `;
                urlList.appendChild(urlItem);
            }

            // 添加删除事件监听
            const deleteButtons = document.querySelectorAll('.delete-btn');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const name = this.getAttribute('data-name');
                    deleteUrl(name);
                });
            });

            // 添加激活事件监听
            const activateButtons = document.querySelectorAll('.activate-btn');
            activateButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const url = this.getAttribute('data-url');
                    chrome.runtime.sendMessage({
                        action: 'setActiveUrl',
                        url: url
                    }, function(response) {
                        if (response && response.success) {
                            console.log('已激活地址:', url);
                        }
                    });
                });
            });
        });
    }

    function deleteUrl(name) {
        chrome.storage.local.get('requestUrls', function(data) {
            const urls = data.requestUrls || {};
            delete urls[name];
            chrome.storage.local.set({'requestUrls': urls}, function() {
                loadUrls();
            });
        });
    }
});